package com.example.testservicce.service;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;

import java.io.IOException;

public class MusicPlayService extends Service {
    MediaPlayer mp;
    public class MusicAgency extends Binder{
        public void paly(String path){
            startPlay(path);
        }
        public void stop(){
            stopPlay();
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return new MusicAgency();

    }
    public  void startPlay(String path){
        //
        if(mp!=null){

            if(mp.isPlaying()){
                mp.stop();
            }
            mp.release();

        }

        mp=new MediaPlayer();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            mp.setDataSource(path);
            mp.prepare();
            mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                }
            });
            mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp.release();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public  void stopPlay(){
        if (mp!=null&&mp.isPlaying()){
            mp.pause();
        }
    }
}
